import ConfigParser as config
import os
import pexpect
from urlparse import urlparse

# ---------------------------------------------------------------------------
def get_config(filename):
    cfg = config.SafeConfigParser()

    bundler_defaults = {'hostname': 'esg.ccs.ornl.gov',
                        'port': '40001',
                        'go_dir': '/tmp/CSSEF-scripts.bundler',
                        'credential_filename': 'credential.pem'}

    pubsvc_defaults = {'hostname': 'esg.ccs.ornl.gov',
                        'port': '40001',
                        'go_dir': '/tmp/CSSEF-scripts.pubsvc',
                        'credential_filename': 'credential.pem'}

    if 'bundler' in filename:
        defaults = bundler_defaults
    elif 'pubsvc' in filename:
        defaults = pubsvc_defaults

    for k in defaults.keys():
        cfg.set('DEFAULT', k, defaults[k])
        
    cfg.read([filename])
    return cfg

# ---------------------------------------------------------------------------
def fetch_credential(openid, passwd, dir):
    validate_openid(openid)
    mpxlogon = "%s/esg-myproxy-logon" % dir
    curdir = os.getcwd()
    os.chdir(dir)

    try:
        if os.path.exists('credential.pem'):
            os.unlink('credential.pem')
    except:
        os.rename('credential.pem',
                  'old.cred.pem.%d' % int(time.time()))
        
    rval = True
    try:
        X = pexpect.spawn("%s %s" % (mpxlogon, openid))
        # X.logfile = sys.stdout
        X.expect("Enter MyProxy Password:")
        X.sendline(passwd)
        # print("\r**************************************************************")
        X.expect("Your credential")
        X.expect("has been written to")
        X.expect("Trust roots have been written to")
        X.expect(pexpect.EOF)
        X.close()
    except:
        rval = False
        
    os.chdir(curdir)
    return rval

# ---------------------------------------------------------------------------
def openid_hostname(openid):
    r = urlparse(openid)
    return r.netloc

# ---------------------------------------------------------------------------
def validate_openid(candidate):
    r = urlparse(candidate)
    if r.scheme != 'https':
        raise StandardError("invalid scheme in URL '%s'" % candidate)
    p = r.path.split('/')
    if p[1] != 'esgf-idp' or p[2] != 'openid':
        raise StandardError("invalid path in URL '%s'" % candidate)

